const fs = require('fs');
const https = require('https');
const path = require('path');

// 创建目录函数
function ensureDirectoryExists(dirPath) {
  if (!fs.existsSync(dirPath)) {
    fs.mkdirSync(dirPath, { recursive: true });
  }
}

// 下载文件函数
function downloadFile(url, destination) {
  return new Promise((resolve, reject) => {
    // 确保目标目录存在
    const dir = path.dirname(destination);
    ensureDirectoryExists(dir);
    
    // 创建写入流
    const file = fs.createWriteStream(destination);
    
    // 发起请求
    const request = https.get(url, (response) => {
      // 检查状态码
      if (response.statusCode !== 200) {
        reject(new Error(`Failed to download ${url}, status code: ${response.statusCode}`));
        return;
      }
      
      // 将响应流导入文件
      response.pipe(file);
      
      // 文件写入完成
      file.on('finish', () => {
        file.close();
        console.log(`Downloaded: ${url} -> ${destination}`);
        resolve();
      });
    });
    
    // 处理请求错误
    request.on('error', (err) => {
      fs.unlink(destination, () => {}); // 删除不完整的文件
      reject(err);
    });
    
    // 处理文件写入错误
    file.on('error', (err) => {
      fs.unlink(destination, () => {}); // 删除不完整的文件
      reject(err);
    });
  });
}

// 要下载的资源列表
const resources = [
  // Font Awesome CSS
  {
    url: 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css',
    dest: './src/static/css/fontawesome.min.css'
  },
  // Font Awesome 字体文件
  {
    url: 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/webfonts/fa-solid-900.woff2',
    dest: './src/static/webfonts/fa-solid-900.woff2'
  },
  // 图片文件
  {
    url: 'https://images.pexels.com/photos/416528/pexels-photo-416528.jpeg?auto=compress&cs=tinysrgb&w=600',
    dest: './src/static/images/water-bottle.jpg'
  },
  {
    url: 'https://images.pexels.com/photos/4145354/pexels-photo-4145354.jpeg?auto=compress&cs=tinysrgb&w=600',
    dest: './src/static/images/notebook.jpg'
  },
  {
    url: 'https://images.pexels.com/photos/4145146/pexels-photo-4145146.jpeg?auto=compress&cs=tinysrgb&w=600',
    dest: './src/static/images/finance.jpg'
  },
  {
    url: 'https://images.pexels.com/photos/313782/pexels-photo-313782.jpeg?auto=compress&cs=tinysrgb&w=600',
    dest: './src/static/images/analytics.jpg'
  },
  {
    url: 'https://images.pexels.com/photos/872831/pexels-photo-872831.jpeg?auto=compress&cs=tinysrgb&w=600',
    dest: './src/static/images/time-management.jpg'
  }
];

// 下载所有资源
async function downloadAll() {
  for (const resource of resources) {
    try {
      await downloadFile(resource.url, resource.dest);
    } catch (error) {
      console.error(`Error downloading ${resource.url}:`, error.message);
    }
  }
  console.log('All downloads completed!');
}

// 执行下载
downloadAll();